package io.geekidea.boot.system.controller;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import io.geekidea.boot.auth.annotation.Permission;
import io.geekidea.boot.config.properties.FileProperties;
import io.geekidea.boot.framework.response.ApiResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Date;
/**
 * @author geekidea
 * @date 2023/6/18
 **/
@RestController
@RequestMapping("/upload")
@Tag(name = "文件上传")
@RequiredArgsConstructor
public class UploadController {
    private static final Logger log = LoggerFactory.getLogger(UploadController.class);
    private final FileProperties fileProperties;
    /**
     * 文件上传到本地
     *
     * @param multipartFile
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/uploadLocal")
    @Operation(summary = "文件上传到本地")
    @Permission("sys:file:upload-local")
    public ApiResult uploadLocal(MultipartFile multipartFile, HttpServletRequest request) throws Exception {
        String originalFilename = multipartFile.getOriginalFilename();
        log.info("originalFilename: {}", originalFilename);
        // 获取文件后缀
        String extension = FilenameUtils.getExtension(originalFilename);
        // 生成新的文件名
        String newFileName = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_MS_PATTERN) +
                RandomStringUtils.randomNumeric(6) + "." + extension;
        log.info("newFileName: {}", newFileName);
        // 本地文件上传路径
        Path uploadPath = Paths.get(fileProperties.getUploadPath());
        Files.createDirectories(uploadPath);  // 创建目录，如果不存在
        // 构建上传文件的完整路径
        Path uploadFilePath = uploadPath.resolve(newFileName);
        log.info("Upload File Path: {}", uploadFilePath);
        // 保存文件到本地
        Files.copy(multipartFile.getInputStream(), uploadFilePath, StandardCopyOption.REPLACE_EXISTING);
        // 构建访问文件的完整路径
        String accessFullPath = buildAccessFullPath(request, newFileName);
        log.info("Access Full Path: {}", accessFullPath);
        return ApiResult.success(accessFullPath);
    }
    private String buildAccessFullPath(HttpServletRequest request, String newFileName) {
        // 使用 java.net.URI 构建文件访问路径
        URI uri = URI.create(request.getScheme() + "://" + request.getServerName() + ":" +
                request.getServerPort() + "/file/" + newFileName);
        return uri.toString();
    }
}
